import functools
import json
import os

from app.common.utils import singleton
from app.globals import env


def get_feature_config_file():
    cfg_file = os.environ.get('FEATURE_CONFIG_FILE')
    cfg_file = cfg_file or 'feature_default.json'
    base_path = env.cfg_dir
    return os.path.join(base_path, cfg_file)


@singleton
class Features(object):
    class Feature(object):
        def __init__(self, f_name, active):
            self.name = f_name
            self._active = active

        @property
        def active(self):
            return self._active

    def __init__(self, conf_file):
        with open(conf_file, encoding='utf-8') as f:
            self.features_config = json.load(f)
        self.features = {}

    def __call__(self, f_name):
        try:
            return self.features[f_name]
        except KeyError:
            active = self.features_config.get(f_name, False) \
                     and self.features_config.get(f_name).get('active', False)
            self.features[f_name] = self.Feature(f_name, active)
            return self.features[f_name]


features = Features(get_feature_config_file())


def feature_with(f_name):
    def feature_wrapper(func):
        @functools.wraps(func)
        def feature(*args, **kwargs):
            func_return = None
            if features(f_name).active:
                func_return = func(*args, **kwargs)
            return func_return

        return feature

    return feature_wrapper
